/*
	klib_page_alloc.c

	contains functionality for global page allocation/deallocation

	Author: Aidan Goddard 19/8/13
*/

#include"../kernel/headers/page_alloc.h"

// function to allocate a free page
// returns physical address of page
// returns  0 if there are no pages available
PAGE_BASE __KLIB__AllocPage()
{
	// disable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("cli");
	__asm__ __volatile__("":::"memory");

	// get a page
	PAGE_BASE to_return = PopFreePage();

	// enable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("sti");
	__asm__ __volatile__("":::"memory");

	// return the page
	return to_return;
}

// function to free an allocated page
void __KLIB__DeallocPage(PAGE_BASE page)
{
	// disable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("cli");
	__asm__ __volatile__("":::"memory");

	// dealloc the page
	PushFreePage(page);

	// enable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("sti");
	__asm__ __volatile__("":::"memory");

	// finished, return
	return;
}

// function to map a page for hardware I/O
void __KLIB__MapPageForIO(PAGE_BASE page)
{
	// disable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("cli");
	__asm__ __volatile__("":::"memory");

	// map the page
	MarkPageAsMapped(page);

	// enable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("sti");
	__asm__ __volatile__("":::"memory");

	// finished, return
	return;
}

// function to get a the number of pages left in the stack
uint32_t __KLIB__GetFreePageCount()
{
	// disable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("cli");
	__asm__ __volatile__("":::"memory");

	// get the page count
	uint32_t to_return = GetFreePageCount();

	// enable interrupts
	__asm__ __volatile__("":::"memory");
	__asm__ __volatile__("sti");
	__asm__ __volatile__("":::"memory");

	// return the page
	return to_return;
}























